﻿@page "/posts/create"
@page "/posts/create/{createType}"
@page "/posts/{id}/edit"
@attribute [Authorize]
@inherits BasePostPage
@inject MessageService MessageService
@using AcBlog.Client.UI.Components.Renderers
@using OneOf

<Loader OnLoad="@OnLoad">
    <PageContainer Title="@(IsCreate ? "Create Post" : "Edit Post")" PageTitle="@Title">
        <Breadcrumb>
            <Breadcrumb>
                <BreadcrumbItem>
                    <a href="">
                        <MdiIcon Type="@IconNames.Home" />
                        <span>Home</span>
                    </a>
                </BreadcrumbItem>
                <BreadcrumbItem>
                    <a href="@UrlGenerator.Posts()">
                        <MdiIcon Type="@IconNames.Posts" />
                        <span>Posts</span>
                    </a>
                </BreadcrumbItem>
                @if (!IsCreate)
                {
                    <BreadcrumbItem>
                        <a href="@UrlGenerator.Post(Target)">
                            <span>@Target.Id</span>
                        </a>
                    </BreadcrumbItem>
                    <BreadcrumbItem>
                        <span>Edit</span>
                    </BreadcrumbItem>
                }
                else
                {
                    <BreadcrumbItem>
                        <span>Create</span>
                    </BreadcrumbItem>
                }
            </Breadcrumb>
        </Breadcrumb>
        <Extra>
            <Button OnClick="OnPreview">
                Preview
            </Button>
            <Button Type="@ButtonType.Primary" OnClick="OnSubmit">
                @if (IsCreate)
                {
                    <MdiIcon Type="@IconNames.Create"></MdiIcon>
                    <span>Create</span>
                }
                else
                {
                    <MdiIcon Type="@IconNames.Edit"></MdiIcon>
                    <span>Update</span>
                }
            </Button>
            @if (!IsCreate)
            {
                <Popconfirm Title="@("Are you sure delete this post?")" OnConfirm="OnDelete" Placement="@PlacementType.BottomRight">
                    <Button Danger>
                        <MdiIcon Type="@IconNames.Delete"></MdiIcon>
                        <span>Delete</span>
                    </Button>
                </Popconfirm>
            }
        </Extra>
        <ChildContent>
            <Form @ref="form" Model="@model" Layout="@FormLayout.Vertical">
                <FormItem Label="Title">
                    <Input @bind-Value="@context.Title" />
                </FormItem>
                <FormItem Label="Type">
                    <RadioGroup @bind-Value="@context.Type">
                        <Radio RadioButton Value="@(PostType.Article)">Article</Radio>
                        <Radio RadioButton Value="@(PostType.Slides)">Slides</Radio>
                        <Radio RadioButton Value="@(PostType.Note)">Note</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem Label="Category">
                    <Input Placeholder="Input as a/b/c." @bind-Value="@context.CategoryString" />
                </FormItem>
                <FormItem Label="Keywords">
                    <Input Placeholder="Input as a;b;c." @bind-Value="@context.KeywordsString" />
                </FormItem>
                <FormItem Label="Content">
                    <TextArea @bind-Value="@context.Content.Raw" AutoSize="@true" MinRows="10"></TextArea>
                </FormItem> 
            </Form>
            <Drawer Closable Width="600" Visible="@Preview" Placement="right" Title="@("Preview")" OnClose="@(_ => Preview = false)">
                @switch (PreviewPost.Type)
                {
                    case PostType.Article:
                    case PostType.Note:
                        <ArticleRenderer Document="@PreviewPost.Content"></ArticleRenderer>
                        break;
                    case PostType.Slides:
                        <SlidesRenderer Document="@PreviewPost.Content" Style="border: 0; height: 500px; width: 100%"></SlidesRenderer>
                        break;
                    default:
                        break;
                }
            </Drawer>
        </ChildContent>
    </PageContainer>

</Loader>

@code {
    [Parameter]
    public string Id { get; set; }

    [Parameter]
    public string CreateType { get; set; }

    private bool Preview { get; set; }

    private Post PreviewPost { get; set; } = new Post();

    class Model
    {
        public PostType Type { get; set; } = PostType.Article;

        public string Author { get; set; } = string.Empty;

        public Document Content { get; set; } = new Document();

        [Required]
        public string Title { get; set; } = string.Empty;

        public string CategoryString { get; set; }

        public string KeywordsString { get; set; }
    }

    private Model model;

    private Form<Model> form;

    private Post Target { get; set; }

    private bool IsCreate { get; set; }

    private void OnPreview()
    {
        PreviewPost.Type = model.Type;
        PreviewPost.Content.Raw = model.Content.Raw;
        Preview = true;
    }

    private async Task OnLoad()
    {
        Title = "Loading...";
        if (string.IsNullOrWhiteSpace(Id))
        {
            Target = new Post();
            Target.Type = CreateType switch
            {
                "article" => PostType.Article,
                "slides" => PostType.Slides,
                "note" => PostType.Note,
                _ => PostType.Article
            };
            IsCreate = true;
            Title = "New";
        }
        else
        {
            Target = await Service.PostService.Get(Id);
            IsCreate = false;
            Title = "Edit";
        }
        model = new Model
        {
            Author = Target.Author,
            Content = Target.Content,
            Title = Target.Title,
            Type = Target.Type,
            CategoryString = Target.Category.ToString(),
            KeywordsString = Target.Keywords.ToString(),
        };
    }

    private void ModelToTarget()
    {
        Target.Author = model.Author;
        Target.Category = Category.Parse(model.CategoryString);
        Target.Keywords = Keyword.Parse(model.KeywordsString);
        Target.Title = model.Title;
        Target.Content = model.Content;
        Target.Type = model.Type;
    }

    async Task OnDelete()
    {
        if (IsCreate)
            return;
        var pass = await Service.PostService.Delete(Target.Id);
        if (pass)
        {
            _ = MessageService.Success("Deleted post successfully.");
            NavigationManager.NavigateTo($"posts");
        }
        else
        {
            _ = MessageService.Error("Failed to delete post.");
        }
    }

    async Task OnSubmit()
    {
        if (!form.Validate())
        {
            _ = MessageService.Error("Invalid input.");
            return;
        }
        try
        {
            ModelToTarget();
        }
        catch
        {
            _ = MessageService.Error("Invalid input.");
            return;
        }
        Target.ModificationTime = DateTimeOffset.Now;

        if (IsCreate)
        {
            Target.CreationTime = DateTimeOffset.Now;
            var id = await Service.PostService.Create(Target);
            if (id is not null)
            {
                _ = MessageService.Success("Created post successfully.");
                NavigationManager.NavigateTo($"posts/{Uri.EscapeDataString(id)}");
            }
            else
            {
                _ = MessageService.Error("Failed to create post.");
            }
        }
        else
        {
            var pass = await Service.PostService.Update(Target);
            if (pass)
            {
                _ = MessageService.Success("Updated post successfully.");
                NavigationManager.NavigateTo($"posts/{Uri.EscapeDataString(Target.Id)}");
            }
            else
            {
                _ = MessageService.Error("Failed to update post.");
            }
        }
    }
}
